package com.lm.drools.config;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Arrays;

@Configuration
public class DroolsConfig {

    private final ResourceLoader resourceLoader;

    public DroolsConfig(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Bean
    public KieContainer kieContainer() throws IOException {
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();

        // 使用 PathMatchingResourcePatternResolver 解析规则文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] ruleFiles = resolver.getResources("classpath*:rules/*.drl");

        // 将所有规则文件添加到 KieFileSystem
        Arrays.stream(ruleFiles).forEach(ruleFile -> {
            try {
                kieFileSystem.write(ResourceFactory.newFileResource(ruleFile.getFile()));
            } catch (Exception e) {
                throw new RuntimeException("Error reading rule file: " + ruleFile, e);
            }
        });

        // 构建 KieModule
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        KieModule kieModule = kieBuilder.getKieModule();

        // 返回 KieContainer
        return kieServices.newKieContainer(kieModule.getReleaseId());
    }
}